﻿using System;
using System.Windows;
using Microsoft.Win32;

namespace Manager
{
	public partial class MainWindow : Window
	{
		string currentDir;
		MadiManager manager;

		public MainWindow()
		{
			InitializeComponent();
			tabControl.Visibility = Visibility.Hidden;
			bGuardar.IsEnabled = false;
			bGuardarComo.IsEnabled = false;
			currentDir = AppDomain.CurrentDomain.BaseDirectory;
			manager = MadiManager.get();
		}

		private void notImplemented()
		{
			MessageBoxResult result =
				  MessageBox.Show(
					"Esta operación no está disponible.",
					"No implementado",
					MessageBoxButton.OK,
					MessageBoxImage.Information);
		}
		private void bSalir_Click(object sender, RoutedEventArgs e)
		{
			this.Close();
		}
		private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
		{
			// If data is dirty, notify user and ask for a response

			if (manager != null && manager.isModified)
			{
				MessageBoxResult result =
				  MessageBox.Show(
					"No has guardado los cambios. ¿Salir sin guardar?",
					"Salir",
					MessageBoxButton.YesNo,
					MessageBoxImage.Warning);
				if (result == MessageBoxResult.No)
					e.Cancel = true;
			}
		}
		private void bNuevo_Click(object sender, RoutedEventArgs e)
		{
			notImplemented();
		}
		private void bAbrir_Click(object sender, RoutedEventArgs e)
		{
			OpenFileDialog dialogo = new OpenFileDialog();
			dialogo.InitialDirectory = currentDir;
			dialogo.Filter = "Archivos madiManager (*.xml)|*.xml";
			dialogo.RestoreDirectory = true;
			Nullable<bool> result = dialogo.ShowDialog();

			if (result == true)
			{
				manager.open(dialogo.FileName);
				tabControl.Visibility = Visibility.Visible;
				bGuardar.IsEnabled = true;
				bGuardarComo.IsEnabled = true;
				updateFields();
			}
		}

		private void bGuardarComo_Click(object sender, RoutedEventArgs e)
		{
			SaveFileDialog dialogo = new SaveFileDialog();
			dialogo.InitialDirectory = currentDir;
			dialogo.Filter = "Archivos madiManager (*.xml)|*.xml";
			dialogo.RestoreDirectory = true;
			Nullable<bool> result = dialogo.ShowDialog();

			if (result == true)
				manager.saveAs(dialogo.FileName);
		}

		private void bGuardar_Click(object sender, RoutedEventArgs e)
		{
			if (manager.isModified)
				manager.save();
		}

		private void updateFields()
		{
			panelInformation.updateFields();
			panelRaces.updateFields();
			panelAttributes.updateFields();
			manager.isModified = false;
		}
	}
}
